<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>文件上传</title>
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width,user-scalable=yes, minimum-scale=1, initial-scale=0.8,target-densitydpi=low-dpi" />
    <meta http-equiv="Cache-Control" content="no-siteapp" />
    <link rel="shortcut icon" href="css/favicon.ico" type="image/x-icon" />
    <link rel="stylesheet" href="layui/css/layui.css" media="all">
    <link rel="stylesheet" href="x-admin/css/font.css">
    <link rel="stylesheet" href="x-admin/css/xadmin.css">
    <script type="text/javascript" src="js/jquery-3.2.3.min.js"></script>
    <script type="text/javascript" src="layui/layui.all.js"></script>
    <link href="css/webuploader.css" rel="stylesheet" />
    <script language="JavaScript" src="js/webuploader.js"></script>

    <script>
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 B';
            var k = 1024;
            sizes = ['B','KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
            i = Math.floor(Math.log(bytes) / Math.log(k));
            var num = bytes / Math.pow(k, i);
            return num.toPrecision(3) + ' ' + sizes[i];
            //return (bytes / Math.pow(k, i)) + ' ' + sizes[i];
            //toPrecision(3) 后面保留一位小数，如1.0GB //return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
        }
    </script>
</head>
<body>


<div  id="extend-upload-chooseFile" style="float: left;margin-left: 5px;margin-top: 5px;">选择文件</div>

<button id="extent-button-uploader" class="layui-btn" style="height: 37px;margin-top: 5px;margin-left: 5px;">开始上传</button>
<div style="width: 800px;">
    <table style="margin-top:10px; " class="layui-table" id="extend-uploader-form" lay-filter="extend-uploader-form"></table>
</div>
<script type="text/html" id="button-form-uploadTalbe">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<div style="display:none" id="UploadhiddenInput" ></div>
<script>
    var uploader;

    function setTableBtn(fileId,val) {
        var td = getTableHead('oper');
        //获取操作栏,修改其状态
        var table = $("#extend-uploader-form").next().find('div[class="layui-table-body layui-table-main"]').find('table');
        var pro = table.find('td[data-field="progress"]');
        for (var i = 0; i < pro.length; i++) {
            var d = $(pro[i]).attr('data-content');
            if (d == fileId) {
                var t = $(pro[i]).next();
                t.empty();
                t.append('<div class="' + td + '"><a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="ok">' + val + '</a></div>')
            }
        }
    }

    function getTableHead(field) {
        //获取table头的单元格class,保证动态设置table内容后单元格不变形
        var div = $("#extend-uploader-form").next().find('div[class="layui-table-header"]');
        var div2 = div[0];
        var table = $(div2).find('table');
        var td = table.find('th[data-field="'+field+'"]').find('div').attr('class');
        return td;
    };

    layui.use(['layer','laytpl','table','element'], function () {
        var table = layui.table;
        var element = layui.element;
        var layer=layui.layer;
        var rowData=[];
        var $hiddenInput = $('#UploadhiddenInput');

        //方法级渲染
        table.render({
            id: 'extend-uploader-form',
            elem: '#extend-uploader-form'
            , url: ''
            , cols: [[
                {type: 'numbers', fixed: 'left'}
                , {field: 'fileName', width: 150, title: '文件名称'}
                , {field: 'fileSize', width: 100, title: '文件大小'}
                , {field: 'validateMd5', title: '上传时间', width: 100, align: 'center'}
                , {
                    field: 'progress', width: 200, title: '进度', templet: function (d) {
                        return '<div style="margin-top: 5px;" class="layui-progress layui-progress-big" lay-filter="' + d.fileId + '"  lay-showPercent="true">' +
                            '<div class="layui-progress-bar layui-bg-blue" lay-percent="0%"></div>' +
                            '</div>'
                    }
                }
                , {field: 'oper', width: 100, title: '操作', toolbar: '#button-form-uploadTalbe'}
            ]]
        });

        WebUploader.Uploader.register({
            "before-send-file":"beforeSendFile"
        },{
            beforeSendFile: function(file,formData){

                // .progress(function(percentage){
                //         alert(2);
                //         var v = that.getTableHead('validateMd5');
                //         var table = $("#extend-uploader-form").next().find('div[class="layui-table-body layui-table-main"]').find('table');
                //         var pro = table.find('td[data-field="progress"]');
                //         for(var i=0;i<pro.length;i++){
                //             var d = $(pro[i]).attr('data-content');
                //             if(d==file.id ){
                //                 var t = $(pro[i]).prev();
                //                 t.empty();
                //                 t.append('<div class="'+v+'">'+(percentage * 100).toFixed(0)+'%</div>');
                //             }
                //         }
                //     })

                var task = new $.Deferred();

                uploader.md5File(file,0,15*1024*1024).then(function(val){
                    $.ajax({
                        type: "GET",
                        //生产
                        // csfile.szoa.sz.gov.cn
                        url:
                            'http://file.guohai110.com/file/md5CheckUpload?identityId=admin&token=123456',
                        // 生产 csfile.szoa.sz.gov.cn
                        // url: 'https://csfile.szoa.sz.gov.cn/file/md5CheckUpload?identityId=admin&token=123456',
                        //安全测评和审计
                        // url: 'https://aqcpfile.szoa.sz.gov.cn/file/md5CheckUpload?identityId=admin&token=123456',
                        //演示
                        //   url:'https://10.248.79.151/file/md5CheckUpload?identityId=admin&token=123456',
                        //联调
                        //  url: 'http://10.248.71.211/file/md5CheckUpload?identityId=admin&token=123456',
                        //文件迁移测试地址
                        //  url: 'https://10.15.255.5:1443/file/md5CheckUpload?identityId=admin&token=123456',
                        //  url:
                             // 'https://10.2.57.77:8083/file/md5CheckUpload?identityId=admin&token=123456',
                         data: {
                            md5: val,fileSize:file.size,userId:'personalCapital',moduleName:'moduleNameB',fileSrcName:file.name  //后台接收 String md5
                        }
                        , cache: false
                        , timeout: 3000
                        , dataType: "json"
                    }).then(function(data, textStatus, jqXHR){
                        console.log("sss");
                        console.log(data,textStatus)
                        console.log(val)
                        console.log(file.size)
                        console.log(file.name)
                        //debugger;
                        if(data.message==0){   //若存在，这返回失败给WebUploader，(后台操作)表明该文件不需要上传，然后就可以把数据库查询出的文件信息的物理路径给新文件
                            task.reject(); //
                            uploader.skipFile(file);
                            setTableBtn(file.id,'秒传');
                            element.progress(file.id, '100%');
                            $hiddenInput.append('<input type="text" id="hiddenInput' + file.id + '" class="hiddenInput" value="' + data.url + '" />');
                        }else{
                            uploader.options.formData={md5:val,fileSize:file.size,userId:'personalCapital',moduleName:'moduleNameB'};
                            task.resolve();
                        }
                    }, function(jqXHR, textStatus, errorThrown){
                        //任何形式的验证失败，都触发重新上传
                        task.resolve();
                    });
                });
                return $.when(task);
            }
        });

        uploader = WebUploader.create({
            // 不压缩image
            resize: false,
            // swf文件路径
            //swf:  '/static/js/Uploader.swf',
            // 默认文件接收服务端。
            //  演示
            // server:'https://10.248.79.151/file/uploadDfs?identityId=admin&token=123456',
            //联调
            // server: 'http://10.248.71.211/file/uploadDfs?identityId=admin&token=123456',
            //文件迁移测试地址
            server: 'http://file.guohai110.com/file/uploadDfs?identityId=admin&token=123456',
            //生产
            // csfile.szoa.sz.gov.cn
            // server: 'https://csfile.szoa.sz.gov.cn/file/uploadDfs?identityId=admin&token=123456',
            //生产
            // csfile.szoa.sz.gov.cn
            // server:
            //     'https://10.2.57.77:8083/file/uploadDfs?identityId=admin&token=123456',
            // server: 'https://aqcpfile.szoa.sz.gov.cn/file/uploadDfs?identityId=admin&token=123456',
            pick: '#extend-upload-chooseFile',
            fileSingleSizeLimit:600*1024*1024,//单个文件大小
            fileSizeLimit: 1000*1024*1024,//验证文件总大小是否超出限制, 超出则不允许加入队列。
            // formData: {md5:'',fileSize:0},
            //接收文件类型--自行添加options
            //验证文件总数量, 超出则不允许加入队列。
            fileNumLimit:10,
            prepareNextFile: true,
            //去重， 根据文件名字、文件大小和最后修改时间来生成hash Key
            //true为可重复   ，false为不可重复
            duplicate:false,
            accept:[{
                title: 'file',
                extensions: 'doc,docx,pdf,xls,xlsx,ppt,pptx,gif,jpg,jpeg,bmp,png,rar,zip,txt',
                mimeTypes: '.doc,.docx,.pdf,.xls,.xlsx,.p pt,.pptx,.gif,.jpg,.jpeg,.bmp,.png,.rar,.zip,.txt'
            }]
        });

        uploader.on('fileQueued', function( file ){
            var fileSize = formatFileSize( file.size, 2, [ 'KB', 'MB'] ) ;
            var row={fileId:file.id,fileName:file.name,fileSize:fileSize,validateMd5:'0%',progress:file.id,state:'就绪'};
            rowData.push(row);
            layui.table.reload('extend-uploader-form',{
                data : rowData
            });
            element.render('progress');
            // element.progress(file.id, '100%');
        });

        uploader.on( 'uploadProgress', function( file, percentage ) {
            element.progress(file.id, (percentage * 100).toFixed(0)+'%');

        });

        //错误信息监听
        uploader.on('error', function(handler){
            if(handler=='F_EXCEED_SIZE'){
                layer.msg('上传的单个太大!。操作无法进行,如有需求请联系管理员', {icon: 5});
            }else if(handler=='Q_TYPE_DENIED'){
                layer.msg('不允许上传此类文件!操作无法进行,如有需求请联系管理员', {icon: 5});
            }else{
                layer.msg(handler, {icon: 3});
            }
        });

        //移除上传的文件
        table.on('tool(extend-uploader-form)', function(obj){
            var data = obj.data;
            if(obj.event === 'del'){
                for(var i=0;i<rowData.length;i++){
                    if(rowData[i].fileId==data.fileId){
                        rowData.splice(i,1);
                    }
                }
                $("#hiddenInput" + data.fileId).remove();
                uploader.removeFile(data.fileId,true);
                obj.del();
            }
        });

        //开始上传
        $("#extent-button-uploader").click(function () {
            if(rowData.length<=0){
                layer.msg('没有上传的文件', {icon: 5});
                return;
            }
            $("#extent-button-uploader").text("正在上传");
            $("#extent-button-uploader").addClass('layui-btn-disabled');
            uploader.upload();
        });

        //单个文件上传成功
        uploader.on( 'uploadSuccess', function( file,data ) {
            setTableBtn(file.id,'完成');
            $hiddenInput.append('<input type="text" id="hiddenInput' + file.id + '" class="hiddenInput" value="' + data.url + '" />')
        });

        //所有文件上传成功后
        uploader.on('uploadFinished',function(){//成功后
            $("#extent-button-uploader").text("开始上传");
            $("#extent-button-uploader").removeClass('layui-btn-disabled');
        });
    });
</script>
</body>
</html>